import { getToken, setJsToken, removeToken } from '@/utils/token'
import router, { resetRouter } from '../../router'
import {
  login,
  getPid,
  logout
} from '@/api/login'

const state = {
  token: getToken(),
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
// user login
  login({
    commit
  }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const orgList = []
        response.data.organizes.forEach(item => {
          const { deptId, entId, label, orgId } = item
          orgList.push({
            sltEntId: entId,
            sltOrgId: orgId,
            sltDeptId: deptId,
            orgName: label
          })
        })
        commit('SET_TOKEN', response.data.token)
        setJsToken(response.data.token)
        resolve(orgList)
      }).catch(error => {
        reject(error)
      })
    })
  },
  subLogin({
    commit,
    state
  }, orgInfo) {
    return new Promise((resolve, reject) => {
      const { orgName } = orgInfo
      sessionStorage.setItem('orgName', orgName)
      getPid(Object.assign({}, orgInfo, { token: state.token })).then(res => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        sessionStorage.removeItem('orgName') // 删除机构
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_ROLES', ['editor'])
      resolve({ roles: ['editor'] })
    })
  },
  changeRoles({ commit, dispatch }) {
    return new Promise(async(resolve, reject) => {
      const { roles } = await dispatch('getInfo')
      resetRouter()

      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      router.addRoutes(accessRoutes)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
